# 编写程序自动下载 github 上星数最多的 python 项目信息，并进行可视化

# 使用 api 调用请求数据
"""https://api.github.com/search/repositories?q=language:python+sort:stars
https://api.github.com/search/repositories 表示地址
？表示要输入参数
q=表示指定查询
language:python是查询内容
+sort：starts 按照星星排序"""
import json

# 安装 requests
"""pip3 install requests --break-system-packages"""

# 处理 api 响应
import requests
    # 执行 api 调用并查看响应
url = "https://api.github.com/search/repositories"
url += "?q=language:python+sort:stars+stars:>10000" ## 太长所以分成了两行
headers = {"Accept":"application/vnd.github.v3+json"}
r = requests.get(url,headers)
print(f"Status code: {r.status_code}")
    # 将响应转换成字典
response_dict = r.json()
print(r)
print(type(r))
print(type(response_dict))
    #处理结果
print(response_dict.keys())
#print(response_dict)
print(len(response_dict["items"])) #共 507个仓库满足，但 github 只返回了前 30个，需要获取更多仓库信息，可请求额外的数据页

    # 保存到文件查看
from pathlib import Path
path = Path("../files/stars10000.json")
content = json.dumps(response_dict,indent=4)
path.write_text(content)

# 处理响应字典
import requests

response_dict = r.json()
print(f"Total repositories: {response_dict["total_count"]}")
print(f"Complete results : {not response_dict["incomplete_results"]}")

    #搜索有关仓库信息
repo_dicts = response_dict["items"]
print(f"Repositories returned: {len(repo_dicts)}")

    #研究第一个仓库
repo_dict = repo_dicts[0]
print(f"\nKeys: {len(repo_dict)}")
for key in sorted(repo_dict.keys()):
    print(key)

print("\nSelected information about first repository:")
print(f"Name: {repo_dict["name"]}")
print(f"Owner: {repo_dict["owner"]["login"]}")
print(f"Stars: {repo_dict["stargazers_count"]}")
print(f"Repository: {repo_dict["html_url"]}")
print(f"Created: {repo_dict["created_at"]}")
print(f"Updated: {repo_dict["updated_at"]}")
print(f"Description: {repo_dict["description"]}")

# 概述最受欢迎的仓库
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")
print("\nSelected information about each repository:")
for repo_dict in repo_dicts:
    print(f"\nName: {repo_dict["name"]}")
    print(f"Owner: {repo_dict["owner"]["login"]}")
    print(f"Stars: {repo_dict["stargazers_count"]}")
    print(f"Repository: {repo_dict["html_url"]}")
    print(f"Created: {repo_dict["created_at"]}")
    print(f"Updated: {repo_dict["updated_at"]}")
    print(f"Description: {repo_dict["description"]}")

# 监控 api 的速率限制
"""访问：https://api.github.com/rate_limit"""

